/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package calculator;

import java.util.LinkedList;


/**
 *
 * @author sd
 */
public class Expression extends LinkedList<NumSign>
{

    @Override
    public String toString() {
        String str="";
        for(NumSign numSign:this)
        {
            str=str+numSign.getStrNum()+numSign.getSign();
        }
        return str;
    }
    
    public double calculate()
    {
        calMulAndDiv();
        calAddAndSub();
        return this.get(0).getNum();
    }
    
    private void calMulAndDiv()
    {
        for(int i=0;i<this.size();i++)
        {
            System.out.println(this.toString());
            if(this.size()==1) return;
            if(this.get(i).getSign()=='*')
            {
                double temp=this.get(i).getNum()*this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
            if(this.get(i).getSign()=='/')
            {
                double temp=this.get(i).getNum()/this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
        }
        
     
    }  private void calAddAndSub()
    {
        for(int i=0;i<this.size();i++)
        {
            System.out.println(this.toString());
            if(this.size()==1) return;
            if(this.get(i).getSign()=='+')
            {
                double temp=this.get(i).getNum()+this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
            if(this.get(i).getSign()=='-')
            {
                double temp=this.get(i).getNum()-this.get(i+1).getNum();
                this.get(i+1).setNum(temp);
                this.remove(i);
                i=-1;
                continue;
            }
        }
        
    }
    
}
